<template>
  <div class="xiecheng">
    <div class="admin_main_block">
      <div class="admin_main_block_top">
        <div class="admin_main_block_left">
          <div>{{ i18n('kernel.role.from') }}</div>
        </div>

        <div class="admin_main_block_right">
          <div>
            <el-button icon="Back" @click="router.go(-1)">
              {{ i18n('common.return') }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="admin_form_main">
        <el-form label-width="120px" ref="formRef" :model="dataForm" :rules="dataRule">
          <el-form-item :label="i18n('kernel.role.title')" prop="title">
            <el-input v-model="dataForm.title" :placeholder="i18n('common.please_input') + i18n('kernel.role.title')"></el-input>
          </el-form-item>

          <el-form-item :label="i18n('kernel.role.content')" prop="content">
            <el-input v-model="dataForm.content" type="textarea" maxlength="200" show-word-limit :placeholder="i18n('common.please_input') + i18n('kernel.role.content')"></el-input>
          </el-form-item>

          <el-form-item>
            <el-divider content-position="left">
              {{ i18n('kernel.role.menu') }}
            </el-divider>
          </el-form-item>

          <el-form-item>
            <div class="ml24">
              <el-checkbox class="mr10" :indeterminate="isIndeterminate" @change="checkedAll" v-model="checkedMenu"/>
              <span>全选 / 取消</span>
            </div>
            <el-tree
              ref="menuListTree"
              :data="menuList"
              :props="menuListTreeProps"
              node-key="id"
              highlight-current
              :default-expand-all="false"
              show-checkbox>
            </el-tree>
          </el-form-item>

          <el-form-item>
            <el-button v-if="isAuth('kernel:role:handle')" type="primary" @click="dataFormSubmit(formRef)">
              {{ i18n('common.confirm') }}
            </el-button>
            <el-button @click="resetForm(formRef)">
              {{ i18n('common.reset') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup name="role-form">
  import { useBase } from "@/hooks/base/useBase"
  import { useForm } from "@/hooks/form/useForm"
  import { isEmpty } from '@/utils/validate'
  import { treeDataTranslate } from '@/utils/library'

  const { router, query, i18n, isAuth } = useBase()

  const model = ref('kernel/role')

  const menuList = ref([])

  const menuListId = ref([])

  const menuListTreeProps = reactive({
    label: 'remark',
    children: 'children',
  })

  const menuListTree = ref([])
  const isIndeterminate = ref(false)
  const checkedMenu = ref(false)

  const dataForm = reactive({
    id: 0,
    organization_id: '',
    title: '',
    content: '',
  })

  const dataRule = reactive({
    title: [{
      required: true,
      message: i18n('kernel.user.rules.username.require'),
      trigger: 'blur',
    }],
  })

  const {
    formRef,
    resetForm
  } = useForm(model.value, dataForm)

  const init = (form) => {
    dataForm.id = query.id || 0

    nextTick(() => {
      form.value.resetFields()
      if (dataForm.id) {
        $http({
          url: $http.adornUrl(`/kernel/role/view/${dataForm.id}`),
          method: 'get',
          params: $http.adornParams({}),
        }).then(({ data }) => {
          if (data.data && data.status === 200) {
            dataForm.id = data.data.id
            dataForm.organization_id = data.data.organization_id
            dataForm.title = data.data.title
            dataForm.content = data.data.content
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/kernel/role/permission/${dataForm.id}`),
              method: 'get',
              params: $http.adornParams(),
            }).then(({ data }) => {
              if (data && data.status === 200) {
                checkedMenu.value = menuListId.length === data.data.permission.length

                // menuListTree.value.setCheckedKeys(data.data.permission)
                data.data.permission.forEach((i, n) => {
                  var node = menuListTree.value.getNode(i)

                  if (!isEmpty(node) && node.isLeaf) {
                    menuListTree.value.setChecked(node, true)
                  }
                })
              }
            })
          }
        })
      }
    })
  }


  // 表单提交
  const dataFormSubmit = (form) => {
    form.validate(async (valid, fields) => {
      if (valid) {
        $http({
          url: $http.adornUrl('/kernel/role/handle'),
          method: 'post',
          data: $http.adornData({
            id: dataForm.id || undefined,
            organization_id: dataForm.organization_id,
            title: dataForm.title,
            content: dataForm.content,
            menu_id: [].concat(
              menuListTree.value.getCheckedKeys(),
              menuListTree.value.getHalfCheckedKeys()
            ),
          }),
        }).then(({ data }) => {
          if (data && data.status === 200) {
            $message.success(i18n('common.handle_success'))
            router.go(-1)
          } else {
            $message.error(data.message)
          }
        })
      }
    })
  }


  const loadMenuList = () => {
    $http({
      url: $http.adornUrl('/menu/select'),
      method: 'get',
      params: $http.adornParams({
        category: 1
      }),
    }).then(({ data }) => {
      menuList.value = treeDataTranslate(data.data.menu)
      menuListId.value = data.data.all_menu_id
    })
    .then(() => {
      nextTick(() => {
        // menuListTree.value.resetFields()
        menuListTree.value.setCheckedKeys([])
      })
    })
  }

  const checkedAll = () => {
    if (checkedMenu.value) {
      //全选
      menuListTree.value.setCheckedKeys(menuListId.value)
      isIndeterminate.value = false
    } else {
      //取消选中
      menuListTree.value.setCheckedKeys([])
      isIndeterminate.value = false
    }
  }

  onMounted(() => {
    init(formRef)
    loadMenuList()
  })
</script>
